<?php
namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Config;
use think\Controller;

class Purchase extends Base
{	
	/**
     * 待分配商品列表
     * @return [type] [description]
     */
    function index(){
    	$keywords = Request()->get('keywords');
        $Query = Db::field('g.*,sval.*,b.brand_name,st.stock_num')
        ->table('sdzx_goods')->alias('g')
        ->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
        // ->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
        ->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
		->join('sdzx_stock st','st.specval_id = sval.specval_id','left')
        // ->order('s.supplier_id  asc')
        ->where("sval.stock<0 and sval.supplier_id=0");
        if ($keywords) {
			$Query->where("g.goods_name like '%{$keywords}%' ");
		}

       	$data['list']['purchase'] = $Query->select();

        $Squery = Db::field('og.*,sum(og.num) as num')
        ->table('sdzx_order_goods')->alias('og')
        ->join('sdzx_supplier_order so','og.order_id=so.order_id')
        ->where("(og.status=-1 or so.order_status in(-1,10)) and og.supplier_id is not null")
        ->order('og.supplier_id')
        ->group('og.goods_specval_id');
        if ($keywords) {
            $Squery->where("og.goods_name like '%{$keywords}%' ");
        }

        $data['list']['supplier'] = $Squery->select();

        // p($data);
       	return $this->fetch('index',$data);
    }

    /**
     * 供应商未接单 或者 缺货商品 则需要采购
     * @return [type] [description]
     */
    public function supplierCancel()
    {
        $keywords = Request()->get('keywords');

        $list=$Query->select();
    }

    /**
     * 分配
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function allot()
    {
    	if (Request()->isPost()) {
    		$param = Request()->param();
    		if (!isset($param['uid']) || empty($param['uid'])) {
    			$this->error('未选择配送员');
    		}

    		if (!isset($param['specval_id']) || empty($param['specval_id'])) {
    			$this->error('未选择采购商品');
    		}

    		//员工信息
    		$employee = DB::name('employee')->where(['id'=>$param['uid'],'deleted'=>0,'status'=>1])->find();
    		if (!$employee) {
    			$this->error('配送员不存在或已禁用');
    		}
    		$time = date('Y-m-d H:i:s');
    		$Purchase = [
				'employee_name' => $employee['name'],
				'employee_id'   => $employee['id'],
				'create_time'   => $time,
				'create_id'     => $this->uid,
				'create_name'   => $this->user['name']
    		];

    		Db::startTrans();
    		$PurchaseId = Db::name('purchase')->insertGetId($Purchase);
    		if (!$PurchaseId) {
    			Db::rollback(); $this->error('分配失败');
    		}

    		//查出商品
    		$goods = Db::field('g.goods_id,g.goods_name,g.picture,sval.supplier_id,sval.price,sval.specval_id,sval.specval_name,sval.spec_name,sval.purchase_price as last_price,sval.stock as num,b.brand_name,b.brand_id')
    		->table('sdzx_goods')->alias('g')
    		->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
    		->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
    		->where(['specval_id'=>['in',$param['specval_id']]])
    		->select();
    		if (!$goods) {
    			Db::rollback(); $this->error('商品不存在');
    		}
    		foreach ($goods as $k => $v) {
				$goods[$k]['purchase_id'] = $PurchaseId;
				$goods[$k]['num']         = $v['num']*-1;
				$goods[$k]['create_time']        = $time;
    		}
    		
    		$re = Db::name('purchase_goods')->insertAll($goods);
    		if (!$re) {
    			Db::rollback(); $this->error('分配失败');
    		}

    		//减需采购的数量
    		foreach ($goods as $k => $v) {
				$r = Db::connect([],'sval')->name('goods_specval')->where(['specval_id'=>$v['specval_id']])->setInc('stock',$v['num']);
				if ($r===false) {
					Db::rollback(); $this->error('分配失败');
				}
    		}



            vendor("pushDemo.demo");
            define('CID',$employee['client_id']);
            pushMessageToSingle();
    		Db::commit(); $this->success('分配成功','',['PurchaseId'=>$PurchaseId]);
    	}else{
            // 采购人员
            $list = Db::field('e.id,e.nickname,e.name,e.phone,g.code')
            ->table('sdzx_employee')->alias('e')
            ->join('sdzx_employee_group_relation r','e.id=r.uid')
            ->join('sdzx_employee_group g','r.group_id=g.id')
            ->where("g.code='CG' and e.status=1 and e.deleted=0")
            ->group('e.id')
            ->select();

            foreach ($list as $k => $v) {
                $list[$k]['num'] = Db::connect([],'emp')->name('purchase')->where(['employee_id'=>$v['id'],'status'=>0])->value('count(purchase_id)');
            }
    		return $this->fetch('allot',['list'=>$list]);
    	}
    }

    /**
     * 采购订单
     * @return [type] [description]
     */
    public function order()
    {
        $keywords = Request()->get('keywords');
        $sort = Request()->get('create_time')?Request()->get('create_time'):"create_time asc";
        $this->assign('sort',$sort);

        $uid = $this->uid;
        $Query = Db::name('purchase')->where('status=0');

        if ($keywords) {
            $Query->where("employee_name like '%{$keywords}%' or create_name like '%{$keywords}%' ");
        }
        $list = $Query->order($sort)->select();

        return $this->fetch('order',['list'=>$list]);
    }

    /**
     * 已完成订单
     * @return [type] [description]
     */
    function finish(){
        $keywords = Request()->get('keywords');
        $uid = $this->uid;
        $Query = Db::name('purchase')->where('status=1');

        if ($keywords) {
            $Query->where("employee_name like '%{$keywords}%' or create_name like '%{$keywords}%' ");
        }
        $list = $Query->order('purchase_id asc')->paginate('',false,['query'=>Request()->param()]);

        return $this->fetch('finish',['list'=>$list]);
    }


    /**
     * 商品列表
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function goods()
    {
    	$params = Request()->param();
    	$uid = $this->uid;

    	$Query = Db::field('pg.*,s.supplier_name')
        ->table('sdzx_purchase_goods')->alias('pg')
        ->join('sdzx_supplier s','pg.supplier_id=s.supplier_id','left')
        ->order('s.supplier_id asc');

    	if (isset($params['purchase_id'])) {
    		$Query->where("purchase_id={$params['purchase_id']}");
    	}

    	if (isset($params['keywords'])) {
			$Query->where("goods_name like '%{$keywords}%' ");
		}

    	$list = $Query->order('purchase_id asc')->where('pg.status',0)->select();
		$this->assign('status',1000);
    	return $this->fetch('goods',['list'=>$list]);
    }

    /**
     * 支付状态
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function paystatus()
    {
        $param = Request()->param();
        !$param['pg_id'] && $this->error('操作失败');
        $re = Db::name('purchase_goods')->where(['pg_id'=>['in',$param['pg_id']]])->update(['pay_status'=>$param['status']]);
        if ($re===false) {
            $this->error('操作失败');
        }
        $this->success('success','');
    }

    /**
     * 网页打印
     * @return [type] [description]
     */
    function webPrint(){
        $param = Request()->param();
        !$param['ids'] && $this->error('参数错误');

        $goods = Db::field('p.employee_id,s.supplier_name,s.charge_phone,p.employee_name,p.status,p.create_id,p.create_name,g.*')->table('sdzx_purchase')->alias('p')
        ->join('sdzx_purchase_goods g','p.purchase_id=g.purchase_id')
        ->join('sdzx_supplier s','g.supplier_id=s.supplier_id','left')
        ->where("p.purchase_id in ({$param['ids']})")
        ->order('g.supplier_id asc')
        ->select();


        // 根据订单归类
        $order = [];
        foreach ($goods as $k => $v) {
            if ( !isset( $order[$v['purchase_id']]['purchase_id']  ) ) {
                $order[$v['purchase_id']] = [
                    'purchase_id'      => $v['purchase_id'],
                    'employee_name'    => $v['employee_name'],
                    'create_time'      => $v['create_time'],
                    'status'           => $v['status'],
                    'create_name'      => $v['create_name'],
                    'total_price'      => 0,
                    'total_last_price' => 0
                ];
            }
            
            $_tmp = Db::field('o.order_id,o.receiver_name,o.receiver_mobile,og.num,s.shop_name')
            ->table('sdzx_order_goods')->alias('og')
            ->join('sdzx_order o','og.order_id=o.order_id')
            ->join('sdzx_shop s','o.user_id=s.user_id','left')
            ->where("og.goods_specval_id={$v['specval_id']} and o.order_status=30")
            ->select();
            $v['order'] = $_tmp;
            $order[$v['purchase_id']]['list'][] = $v;
            $order[$v['purchase_id']]['total_price'] +=$v['price'];
            $order[$v['purchase_id']]['total_last_price'] +=$v['last_price'];
            $order[$v['purchase_id']]['totalnum'] += $v['num'];
        }
        $data['list'] = $order;
        
        return $this->fetch('webprint',$data);
    }

    /**
     * 打印条码
     * @return [type] [description]
     */
    function webPrintcode(){
        $param = Request()->param();
        !$param['ids'] && $this->error('参数错误');

        $goods = Db::field('p.employee_id,s.supplier_name,s.charge_phone,p.employee_name,p.status,p.create_id,p.create_name,g.*')->table('sdzx_purchase')->alias('p')
        ->join('sdzx_purchase_goods g','p.purchase_id=g.purchase_id')
        ->join('sdzx_supplier s','g.supplier_id=s.supplier_id','left')
        ->where("p.purchase_id in ({$param['ids']})")
        ->order('g.supplier_id asc')
        ->select();

        // 根据订单归类
        $order = [];
        foreach ($goods as $k => $v) {
            if ( !isset( $order[$v['purchase_id']]['purchase_id']  ) ) {
                $order[$v['purchase_id']] = [
                    'purchase_id'      => $v['purchase_id'],
                    'employee_name'    => $v['employee_name'],
                    'create_time'      => $v['create_time'],
                    'status'           => $v['status'],
                    'create_name'      => $v['create_name'],
                    'total_price'      => 0,
                    'total_last_price' => 0
                ];
            }
            $order[$v['purchase_id']]['list'][] = $v;
            $order[$v['purchase_id']]['total_price'] +=$v['price'];
            $order[$v['purchase_id']]['total_last_price'] +=$v['last_price'];
            $order[$v['purchase_id']]['totalnum'] += $v['num'];
        }
        $data['list'] = $order;
        return $this->fetch('',$data);
    }
	
	/**
     * 所有采购订单
     * @return [type] [description]
     */
    public function allorder()
    {
        $keywords = Request()->get('keywords');
        $sort = Request()->get('create_time')?Request()->get('create_time'):"create_time desc";
        $this->assign('sort',$sort);

        $uid = $this->uid;
        $Query = Db::name('purchase');//->where('status=0')

        if ($keywords) {
            $Query->where("employee_name like '%{$keywords}%' or create_name like '%{$keywords}%' ");
        }
        $list = $Query->order($sort)->paginate();
		foreach($list as $key => $val){
			$val['money'] = db('purchase_goods')->field('sum(price*num) as price,sum(cur_price*real_num) as cur_price')->where('purchase_id',$val['purchase_id'])->find();
			$list[$key] = $val;
		}

		$this->assign('status',1000);
        return $this->fetch('order',['list'=>$list]);
    }

    public function cancel()
    {
        $list = Db::field('pg.*,p.employee_name')
        ->table('sdzx_purchase_goods')->alias('pg')
        ->join('sdzx_purchase p','pg.purchase_id=p.purchase_id')
        ->where("pg.status=2")
        ->order('pg.cancel_time asc')
        ->select();
        foreach ($list as $key => $value) {
            $list[$key]['data'] = Db::table('sdzx_order_goods')->alias('og')
            ->field('o.receiver_name,o.order_no,o.create_time')
            ->join('sdzx_order o','o.order_id=og.order_id')
            ->where(['og.goods_id'=>$value['goods_id'],'o.order_status'=>30])
            ->select();
        }
        // dump($list);
        return $this->fetch('',['list'=>$list]);
    }

    public function delCancel()
    {
        $param = Request()->param();

        $re = DB::name('purchase_goods')->where(['pg_id'=>['in',$param['pg_id']]])->update(['status'=>-1]);
        if ($re!==false) {
            $this->success('操作成功，页面刷新中...','refresh');
        }else{
            $this->error('操作失败');
        }
    }

    public function edit_price(){
        $data = Request()->param();
        if (!isset($data['pg_id']) || empty($data['pg_id'])) {
            $this->error('参数错误');
        }
        $map = [];
        if(isset($data['price']) && $data['price']!=null && is_numeric($data['price'])){
            $map['cur_price'] = $data['price'];
        }
        $res = Db::name('purchase_goods')->where('pg_id',$data['pg_id'])->update($map);
        if($res!==false){
            $this->success('操作成功','refresh');
        }else{
            $this->error('操作失败');
        }
    }
}
